<?php
use Illuminate\Support\Facades\Response as FacadesResponse;
use \Illuminate\Database\Eloquent\ModelNotFoundException;


/*
 *@author gaozongwei
*/
class EasemobController extends BaseController{

	protected $layout = 'layouts.master';
	
	protected function checkUser($id){
		$user = User::find($id);
		if(!$user){
			return $this->makeView(
					'errors.404',
					'该用户不存在',
					404
			);
		}
		return $user;
	}
	
	/*
	 * 获取token
	 */
	public function getToken(){
		$result = new Easemob();
		$token = $result->getToken();
		return $this->makeView('general.200', $token, 200);
	}
	
	/*
	 * 取得所有环信服务器用户
	 */
	public function getEasemobUserIds(){
		$limit = '1000';
		$result = new Easemob();
		$easemob_id = array();
		$details = json_decode($result->userAll($limit), true);
		if (!isset($details['entities'])) {
			return [];
		}
		
		$data = $details['entities'];
		foreach($data as $key){
			$easemob_id[] = $key['username'];
		}
		while (isset($details['cursor'])) {
			$details = json_decode($result->userAll($limit, $details['cursor']), true);
			$data = $details['entities'];
			foreach($data as $key){
				$easemob_id[] = $key['username'];
			}
		}
		return $easemob_id;
	}

	/*
	 * 已注册环信的圈子
	 */
	public function easemobGroups() {
		$result = new Easemob();
		$groupList = $result->chatGroups();
		$groupNames = [];
		$groupList = json_decode($groupList, true);
		foreach($groupList['data'] as $group) {
			$groupNames[] = $group['groupname'];
		}
		$query = SNSGroup::whereIn('group_name',$groupNames);
		$groups = $query->get();
		return $this->makeView('easemob.group', array('groups' => $groups->toArray()));
	}

	/*
	 * 未注册环信的圈子
	 */
	public function noEasemobGroups() {
		$result = new Easemob();
		$groupList = $result->chatGroups();
		$groupNames = [];
		$groupList = json_decode($groupList, true);
		foreach($groupList['data'] as $group) {
			$groupNames[] = $group['groupname'];
		}
		$query = SNSGroup::whereNotIn('group_name',$groupNames);
		$groups = $query->get();
		return $this->makeView('easemob.group', array('groups' => $groups->toArray()));
	}
	
	/*
	 * 已注册环信用户
	 */
	public function easemob(){
		$page = isset($_GET['page']) ? intval($_GET['page']) : 1;
		$page_row = 30;		
		$easemob_users = $this->getEasemobUserIds();
		$query = User::whereIn('id',$easemob_users);
		$count = $query->count();
		$total_page = ceil($count/$page_row);
		if($page<1)$page = 1;
		if($page>$total_page)$page = $total_page;
		$offset = ($page-1)*$page_row;
		try{
			$users = $query->take($page_row)->skip($offset)->get();
			$users = $users->toArray();
		}catch(Exception $ex){
			Log::error($ex);
			return $this->makeView('errors.503', '服务器暂时无法响应，请稍后再试', 503);
		}
		return $this->makeView('easemob.user', array('users' => $users, 'page' => $page, 'total_page' => $total_page));
	}
	
	/*
	 * 未注册环信用户
	*/
	public function noEasemob(){
		$page = isset($_GET['page']) ? intval($_GET['page']) : 1;
		$page_row = 30;
		$easemob_users = $this->getEasemobUserIds();
		$query = User::whereNotIn('id',$easemob_users);
		$count = $query->count();
		$total_page = ceil($count/$page_row);
		if($page<1)$page = 1;
		if($page>$total_page)$page = $total_page;
		$offset = ($page-1)*$page_row;
		try{
			$users = $query->take($page_row)->skip($offset)->get();
			$users = $users->toArray();
		}catch(Exception $ex){
			Log::error($ex);
			return $this->makeView('errors.503', '服务器暂时无法响应，请稍后再试', 503);
		}
		return $this->makeView('easemob.user', array('users' => $users, 'page' => $page, 'total_page' => $total_page));
	}
	
	/*
	 * 登录环信
	*/
	public function login(){
		$this->makeView('easemob.easemob');
	}

	/*
	 * 注册环信圈子
	 */
	public function accreditRegisterGroup() {
		$post = Input::get('groupId');
		$groups = array();
		if($post) {
			foreach($post as $key => $groupId){
				$group = SNSGroup::find($groupId);
				$group->load('members');
				$groupArr = $group->toArray();

				$members = [];
				foreach($groupArr['members'] as $member) {
					$members[] = $member['user_id'];	
				}
				
				$groups[] = array(
					'groupname' => $groupArr['group_name'],
					'desc' => '律团',
					'approval' => false,
					'public' => false,
					'owner' => (string)$groupArr['created_by'],
					'members' => $members
				);
			}
		} else {
			return $this->makeView('errors.400', '请选择至少一个圈子', 400);
		}
		
		try{
			$result = new Easemob();
    		$result_re = $result->createGroups($groups);
			$dagg = json_decode($result_re);
			if(isset(json_decode($result_re)->error)){
				return $this->makeView(
					'errors.400',
					'环信注册失败',
					400
				);
			}
		}catch (Exception $ex){
			Log::error($ex);
			return $this->makeView(
				'errors.503',
				'注册失败，请稍后再试',
				503
			);
		}
		return $this->makeView(
			'general.200',
			'环信注册成功'
		);
	}
	
	/*
	 * 删除注册用户
	 */
	public function deleteUsers(){
		$post = Input::get('userId');
		$users = array();
		if($post){
			foreach($post as $key => $userId){
				try{
				    $result = new Easemob();
				    $result_re = $result->deleteUser($userId);
				    $dagg = json_decode($result_re);
				    if(isset(json_decode($result_re)->error)){
				        return $this->makeView(
				            'errors.400',
				            '环信注册失败',
				            400
				            );
				    }
				}catch (Exception $ex){
				    Log::error($ex);
				    return $this->makeView(
				        'errors.503',
				        '注册失败，请稍后再试',
				        503
				        );
				}
			}
		}else{
			return $this->makeView('errors.400', '请选择至少一位用户', 400);
		}
		
		return $this->makeView(
				'general.200',
				'环信删除用户成功'
		);
	}
	
	/*
	 * 更新环信用户的密码
	 */
	public function updatePass(){
		$post = Input::get('userId');
		$users = array();
		if($post){
			foreach($post as $key => $userId){
				$user = User::find($userId);
				$password = Easemob::getPass($user);
				$option = array(
					'username' => $userId,
					'newpassword' => $password,
				);

				try{
				    $result = new Easemob();
				    $result_re = $result->editPassword($option);
				    $dagg = json_decode($result_re);
				    if(isset(json_decode($result_re)->error)){
				        return $this->makeView(
				            'errors.400',
				            '环信注册失败',
				            400
				            );
				    }
				}catch (Exception $ex){
				    Log::error($ex);
				    return $this->makeView(
				        'errors.503',
				        '注册失败，请稍后再试',
				        503
				        );
				}
			}
		}else{
			return $this->makeView('errors.400', '请选择至少一位用户', 400);
		}
		
		return $this->makeView(
				'general.200',
				'环信注册成功'
		);
	}
	
	/*
	 * 注册环信(授权注册模式)
	*/
	public function accreditRegister(){
		$post = Input::get('userId');
		$users = array();
		if($post){
			foreach($post as $key => $userId){
				$user = User::find($userId);
				$nickname = $user->nikname?$user->nikname:$user->realname;
				$users[] = array(
						'username' => $userId,
						'password' => $user->password,
						'nickname' => $nickname				//可不传
					);
			}
		}else{
			return $this->makeView('errors.400', '请选择至少一位用户', 400);
		}
		try{
			$result = new Easemob();
			$result_re = $result->accreditRegister($users);
			$dagg = json_decode($result_re);
			if(isset(json_decode($result_re)->error)){
				return $this->makeView(
						'errors.400',
						'环信注册失败',
						400
					);
			}
		}catch (Exception $ex){
			Log::error($ex);
			return $this->makeView(
					'errors.503',
					'注册失败，请稍后再试',
					503
			);
		}
		return $this->makeView(
				'general.200',
				'环信注册成功'
		);		
	}
	
	/*
	 * 重置密码
	 * @param $options['username'] 用户名        	
	 * @param $options['password'] 密码        	
	 * @param $options['newpassword'] 新密码    
	 */
	public function editPassword(){
		$options['username'] = Auth::user()->id;
		$options['password'] = Auth::user()->password;
		$options['newpassword'] = '1234';
		try{
			$result = new Easemob();
			$result_re = $result->editPassword($options);
		}catch (Exception $ex){
			Log::error($ex);
			return $this->makeView(
				'errors.503',
					'查看失败',
					503	
				);
		}
		return $this->makeView(
				'general.200',
				$data,
				200
		);		
	}

	/*
	 * 查看用户信息
	 */
	public function userDetails($id){
		$user = $this-> checkUser($id);
		try{
			$result = new Easemob();
			$details =json_decode($result->userDetails($id));
			if(isset($details->error)){
				return $this->makeView(
					'errors.404',
					'该用户没有环信账号',
					404
				);
		}
		$data = (array)$details->entities[0];
		}catch (Exception $ex){
			Log::error($ex);
			return $this->makeView(
				'errors.503',
					'查看失败',
					503	
				);
		}
		return $this->makeView(
				'general.200',
				$data,
				200
		);		
	}

	/*
	 * 添加好友
	 */
	public function addFriend($user_id){
		$user = $this->checkuser($user_id);
		try{
			$result = new Easemob();
			$add = $result->addFriend(Auth::user()->id, $user_id);
			$add =json_decode($add);
			if(isset($add->error)){
				return $this->makeView(
					'errors.404',
					'该用户没有环信账号',
					404
				);
			}
			$add = $result->addFriend($user_id, Auth::user()->id);
		}catch (Exception $ex){
			Log::error($ex);
			return $this->makeView('errors.503', '添加失败', 503);
		}
		return $this->makeView('general.200', '添加成功', 200);
	}
	
	/*
	 * 查看好友列表
	 */
	public function listFriend(){
		try{
			$result = new Easemob();
			$friends = $result->showFriend(Auth::user()->id);
			$friends = json_decode($friends);
		}catch (Exception $ex){
			Log::error($ex);
			return $this->makeView(
					'errors.503',
					'查询失败',
					503
			);
		}
		return $this->makeView(
				'general.200',
				$friends,
				200
		);
	}
	
	/*
	 * 删除好友
	 */
	public function removeFriend($user_id){
		$user = $this->checkuser($user_id);
		try{
			$result = new Easemob();
			$remove = $result->deleteFriend(Auth::user()->id, $user_id);
			$remove =json_decode($remove);
			if(isset($remove->error)){
				return $this->makeView('errors.404', '该用户没有环信账号', 404);
			}
			$remove = $result->deleteFriend(Auth::user()->id,$user_id);
		}catch (Exception $ex){
			Log::error($ex);
			return $this->makeView('errors.503', '添加失败', 503);
		}
		return $this->makeView('general.200', '删除成功', 200);
	}
	
	/*
	 * 所有群组列表
	 */
	public function listGroups(){
		try{
			$result = new Easemob();
			$groupList = $result->chatGroups();
		}catch (Exception $ex){
			Log::error($ex);
			return $this->makeView('errors.503', '添加失败', 503);
		}
		return $this->makeView('general.200', $groupList, 200);
	}
	
	/*
	 * 创建群组
	 */
	public function createGroups(){
//		$post = Input::all();
		$option['groupname'] ='加入圈子';					//群组名称,此属性为必须的
	 	$option['desc'] ='dkflk';						//群组描述,此属性为必须的
	 	$option['public'] = true;						//是否是公开群,此属性为必须的 true or false
	 	$option['maxusers'] = '200';					//群最多成员数
	 	$option['approval'] = true;						//加入公开群是否需要批准,没有这个属性的话默认是true, 此属性为可选的
	 	$option['owner'] =(string)7;		//群组的管理员,此属性为必须的
	 	$option['members'] = array();						//群组成员,此属性为可选的        	
		try{
			$result = new Easemob();
			$group = $result->createGroups($option);
			$group = json_decode($group);
			dd($group->data->groupid);
		}catch (Exception $ex){
			Log::error($ex);
			return $this->makeView('errors.503', '创建失败', 503);
		}
		return $this->makeView('general.200', '创建成功', 200);
	}
	
	/*
	 * 修改群组
	 */
	public function setGroups($group_id){
		$option['groupname'] = '2015120400002'; 	//群组名称,此属性为必须的
		$option['description'] = '修改测试'; 			//群组描述,此属性为必须的
		$option['maxusers'] = '300'; 			//群组成员,此属性为可选的
		$result = new Easemob();
		$group = $result->setGroups($option,$group_id);
		dd($group);
	}

	/*
	 * 获取群组详情
	 */
	public function groupDetail($group_id){
		try{
			$result = new Easemob();
			$group = $result->chatGroupsDetails($group_id);
			$group = json_decode($group);
		}catch (Exception $ex){
			Log::error($ex);
			return $this->makeView('errors.503', '请求失败', 503);
		}
		return $this->makeView('', $group, 200);
	}
	
	/*
	 * 删除群组
	 */
	public function removeDetail($group_id){
		try{
			$result = new Easemob();
			$group = $result->deleteGroups($group_id);
			$group = json_decode($group);
		}catch (Exception $ex){
			Log::error($ex);
			return $this->makeView('errors.503', '请求失败', 503);
		}
		return $this->makeView('general.201', '删除成功', 201);
	}
	
	/*
	 * 获取群组成员
	 */
	public function groupsUser($group_id){
		try{
			$result = new Easemob();
			$group = $result->groupsUser($group_id);
			$group = json_decode($group);
		}catch (Exception $ex){
			Log::error($ex);
			return $this->makeView('errors.503', '请求失败', 503);
		}
		return $this->makeView('', $group, 200);
	}
	
	/**
	 * 群组添加成员
	 */
	public function addGroupsUser($group_id, $username){
		try{
			$result = new Easemob();
			$group = $result->addGroupsUser($group_id,$username);
			$group = json_decode($group);
		}catch (Exception $ex){
			Log::error($ex);
			return $this->makeView('errors.503', '请求失败', 503);
		}
		return $this->makeView('', '添加成功', 200);
	}
	
	/*
	 * 群组删除成员
	 */
	
	public function removeGroupsUser($group_id, $username){
		try{
			$result = new Easemob();
			$group = $result->delGroupsUser($group_id,$username);
			$group = json_decode($group);
		}catch (Exception $ex){
			Log::error($ex);
			return $this->makeView('errors.503', '请求失败', 503);
		}
		return $this->makeView('', '删除成功', 200);
	}
	
	/*
	 * 消息记录
	 */
	public function chatRecord($group_id){
//		$ql = "select+*+where+to+=+'$group_id'+order+by+timestamp+desc";
//		$ql = "order+by+timestamp+asc";
//		$ql = "ql=select+*+where+timestamp>1403164734226";
		$ql = "select+*+order+by+timestamp+desc";
		try{
			$result = new Easemob();			
			$messages = $result->chatRecord($ql);
			$messages = json_decode($messages);
			dd($messages);
		}catch (Exception $ex){
			Log::error($ex);
			return $this->makeView('errors.503', '请求失败', 503);
		}
		return $this->makeView('', $messages, 200);
	}
	
	/*
	 * 发送群消息
	 */
	public function send($groupId){
		$content = '很高兴认识你';
		try{
			$result = new Easemob();
			$message = $result->yy_hxSend(Auth::user()->id, [$groupId], $content, $target_type = "users", array());
		}catch (Exception $ex){
			Log::error($ex);
			return $this->makeView('errors.503', '请求失败', 503);
		}
		return $this->makeView('', $message, 200);
	}

}